package com.restkeeper.controller.store;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.restkeeper.exception.BussinessException;
import com.restkeeper.response.page.PageVO;
import com.restkeeper.store.entity.Credit;
import com.restkeeper.store.entity.CreditCompanyUser;
import com.restkeeper.store.entity.CreditLogs;
import com.restkeeper.store.entity.CreditRepayment;
import com.restkeeper.store.service.ICreditLogsService;
import com.restkeeper.store.service.ICreditRepaymentService;
import com.restkeeper.store.service.ICreditService;
import com.restkeeper.utils.BeanListUtils;
import com.restkeeper.vo.store.CreditCompanyUserVO;
import com.restkeeper.vo.store.CreditRepaymentVO;
import com.restkeeper.vo.store.CreditVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Slf4j
@Api(tags = { "挂账管理接口" })
@RestController
@RequestMapping("/credit")
public class CreditController {

    @Reference(version = "1.0.0",check = false)
    private ICreditService creditService;

    @Reference(version = "1.0.0",check = false)
    private ICreditLogsService creditLogsService;

    @Reference(version = "1.0.0", check=false)
    private ICreditRepaymentService creditRepaymentService;

    @ApiOperation(value = "挂账列表")
    @GetMapping("/pageList/{page}/{pageSize}")
    public PageVO<CreditVO> pageList(@RequestParam(value = "name", defaultValue = "") String name, @PathVariable int page, @PathVariable int pageSize){

        IPage<Credit> creditIPage = creditService.queryPage(page, pageSize, name);

        List<CreditVO> voList = Lists.newArrayList();
        try {
            voList = BeanListUtils.copy(creditIPage.getRecords(),CreditVO.class);
        } catch (Exception e) {
            throw new BussinessException("集合转换出错");
        }

        return new PageVO<CreditVO>(creditIPage,voList);
    }

    @ApiOperation(value = "修改挂账状态")
    @PutMapping("/update/{id}/status/{status}")
    public boolean updateCreditStatus(@PathVariable String id, @PathVariable Integer status) {
        return creditService.updateCreditStatus(id,status);
    }

    @ApiOperation(value = "根据id查询挂账（记录）")
    @GetMapping("/creditLog/{page}/{pageSize}/{creditId}")
    public PageVO<CreditLogs> getCreditLogPageList(@PathVariable(value = "creditId") String creditId, @PathVariable int page, @PathVariable int pageSize,
    @RequestParam(value = "startTime", defaultValue = "") String startTime, @RequestParam(value = "endTime", defaultValue = "") String endTime){

        System.out.println("startTime"+startTime+"endTime"+endTime);
        //String转换成LocalDateTime格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate startTimeLocalDate =  LocalDate.parse(startTime, formatter);
        LocalDate endTimeLocalDate =  LocalDate.parse(endTime, formatter);
        LocalDateTime startTime1 = startTimeLocalDate.atTime(0, 0, 0);
        LocalDateTime endTime1 = endTimeLocalDate.atTime(23, 59, 59);
        System.out.println("startTime1:"+startTime1+"endTime1:"+endTime1);

        return new PageVO<CreditLogs>(creditLogsService.queryPage(creditId,page,pageSize,startTime1,endTime1));
    }

    @ApiOperation(value = "添加挂账")
    @PostMapping("/add")
    public boolean add(@RequestBody CreditVO creditvo) {
        //CreditVO->转化成 Credit
        Credit credit = new Credit();
        BeanUtils.copyProperties(creditvo,credit,"users");

        if (creditvo.getUsers()!=null && !creditvo.getUsers().isEmpty()){
            // List<CreditCompanyUserVO> 转换成 List<CreditCompanyUser>
            List<CreditCompanyUser> companyUsers = Lists.newArrayList();
            creditvo.getUsers().forEach(d->{

                CreditCompanyUser creditCompany = new CreditCompanyUser();
                BeanUtils.copyProperties(d,creditCompany);
                companyUsers.add(creditCompany);
            });
            return creditService.addCredit(credit,companyUsers);
        }
        return creditService.addCredit(credit,null);
    }

    @ApiOperation(value = "修改挂账")
    @PutMapping("/update/{id}")
    public boolean updateCredit(@PathVariable String id, @RequestBody CreditVO creditvo) {
        //CreditVO->转化成 Credit
        Credit credit = creditService.getById(id);
        BeanUtils.copyProperties(creditvo,credit,"users");
        if (creditvo.getUsers()!=null && !creditvo.getUsers().isEmpty()){

            // List<CreditCompanyUserVO> 转换成 List<CreditCompanyUser>
            List<CreditCompanyUser> companyUsers = Lists.newArrayList();
            creditvo.getUsers().forEach(d->{
                CreditCompanyUser creditCompany = new CreditCompanyUser();
                BeanUtils.copyProperties(d,creditCompany);
                companyUsers.add(creditCompany);
            });
            return creditService.updateInfo(credit,companyUsers);
        }

        return creditService.updateInfo(credit,null);
    }

    @ApiOperation(value = "挂账还款")
    @PostMapping("/repayment")
    public boolean repayment(@RequestBody CreditRepaymentVO creditRepaymentVo){
        CreditRepayment creditRepayment =new CreditRepayment();
        BeanUtils.copyProperties(creditRepaymentVo,creditRepayment);
        return creditRepaymentService.repayment(creditRepayment);
    }

    @ApiOperation(value = "根据id查询挂账（信息）")
    @GetMapping("/{id}")
    public CreditVO getCredit(@PathVariable String id){
        CreditVO creditVO =new CreditVO();
        Credit credit = creditService.queryById(id);
        BeanUtils.copyProperties(credit,creditVO);
        return creditVO;
    }
}